<template>
  <div class="box-wrap">
    <section class="box-operation">
      <div class="box-search">
        <div class="form-group-enquire">
          <Input
            v-model.trim="searchData.account"
            placeholder="账户"
            clearable
            @on-enter="onSearchGetList()"
          ></Input>
        </div>
        <div class="form-group-enquire">
          <el-select
            v-model="searchData.status"
            placeholder="状态"
            clearable
            filterable
          >
            <el-option
              :value="row.id"
              v-for="row in statuslist"
              :label="row.name"
              :key="row.id"
              >{{ row.name }}</el-option
            >
          </el-select>
        </div>
        <div class="form-group-enquire">
          <el-select
            v-model="business_price_id"
            placeholder="业务方案"
            multiple
            collapse-tags
            clearable
            filterable
          >
            <el-option
              :value="row.id"
              v-for="row in pList"
              :label="row.name"
              :key="row.id"
              >{{ row.name }}</el-option
            >
          </el-select>
        </div>
        <div class="form-group-enquire-date">
          <DatePicker
            type="daterange"
            placeholder="注册时间"
            :editable="false"
            v-model="searchDate"
            @on-change="changeDate"
            @on-clear="initDate"
          ></DatePicker>
        </div>
        <div class="form-group-img" @click="onSearchGetList()">
          <img src="../../assets/images/peach-svg/Frame 23.svg" />
        </div>
        <div class="form-group-addimg" @click="editInfo({}, 1)">
          <img src="../../assets/images/peach-svg/add.svg" />
        </div>
        <div class="form-group-addimg" @click="ppliang({}, 7)">
          <img src="../../assets/images/peach-svg/mach.svg" />
        </div>
      </div>
    </section>
    <LibVxeTable
      class="staticData"
      :stripe="stripe"
      border="none"
      :tableColumns="tableColumns"
      :tableData="list"
      :slotHeader="slotHeader"
      :PageObj="{
        total: totalCnt,
        currentPage: searchData.page_index,
        pageSize: searchData.page_size,
      }"
      @onPageChange="onChangePageSize"
      @onSelectChange="onCheckChange"
      resizable
    ></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import { commonMixin } from "../../components/ViewInitMixin"; //每一个文件都要包含这个
import { TimePicker } from "iview";
import SearchUser from "../searchUser";
import bus from "../../commons/EventBus";
import Request from "../../commons/Request";

export default {
  name: "addUserDetailView", //!!这块一定要注意，每一个文件都根据资源path来命名
  components: { TimePicker, SearchUser },
  mixins: [commonMixin],
  data() {
    const validateaccount = (rule, value, callback) => {
      console.log(value.length, "value.lenth");
      // let s=/^[^\u4e00-\u9fa5]{4,20}$/ //不包含中文4-20位字符
      if (value == "") {
        callback(new Error("账号不能为空"));
      } else if (value.length < 4 || value.length > 20) {
        callback(new Error("账号名称长度在4-20位字符之内"));
      } else {
        callback();
      }
    };
    const validatepasswd = (rule, value, callback) => {
      var s = /^(?![\u4e00-\u9fa5])(?:(?=.*[a-zA-Z])(?=.*\d|.*[@#￥！……$%^&*()_+!~-])|(?=.*\d)(?=.*[a-zA-Z~!@￥！……#$%^&*()_+])|(?=.*[@#￥！……$%^&*()_+~!~-])(?=.*[a-zA-Z\d]))[a-zA-Z\d@￥！……#$%^&*()_+!~-]{8,20}$/;
      if (value == "") {
        callback(new Error("密码不能为空"));
      } else if (s.test(value) == "") {
        callback(
          new Error(
            "密码长度在8-20位字符之内，包含字母、数字、特殊符号其中两种"
          )
        );
      } else {
        callback();
      }
    };
    const validateRole = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("用户角色必须选择"));
      } else {
        callback();
      }
    };
    const validateLeader = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("上级角色必须选择"));
      } else {
        callback();
      }
    };
    return {
      stripe: false,
      statuslist: [
        { id: 1, name: "正常" },
        { id: 2, name: "冻结" },
      ],
      modal: false,
      searchDate: "",
      searchTime: [
        utils.dateFormat(0, "HH") + "00",
        utils.dateFormat(0, "HH") + "00",
      ],
      searchData: {
        account: "",
        page_index: 1,
        page_size: 30,
        create_at: "",
        status: "",
        role_id: "",
        leader_id: "",
        business_price_id: "",
      },
      business_price_id: "",
      pList: [],
      pList2: [],
      priceId: "",
      nameobj: [],
      versionsList: [
        { Id: -1, Name: "全部版本" },
        { Id: 1, Name: "v1" },
        { Id: 2, Name: "v2" },
      ],
      mnoList: {},
      provinceList: {},
      list: [],
      totalCnt: 0,
      info: {},
      selectRows: [],
      channelList: [],
      cityList: [],
      cityInfo: [-1],
      partnerList: [],
      ChannelList: [],
      QdsPartnerList: [],
      QdsPartnerObj: {},
      BusinessList: [],
      BusinessObj: {},
      cityObj: {},
      brandObj: {},
      brandObjCh: {},
      roles: [],
      leaders: [],
      roleList: {},
      rollist: [],
      leaderlist: [],
      eid: "",
      tableColumns: [
        {
          field: "Id",
          type: "checkbox",
          align: "center",
          width: 50,
        },
        {
          title: "序号",
          field: "ids",
          align: "center",
          slots: {
            default: ({ rowIndex, row }, h) => {
              return [
                h(
                  "div",
                  this.searchData.page_size * (this.searchData.page_index - 1) +
                    (rowIndex + 1)
                ),
              ];
            },
          },
        },
        {
          title: "账号",
          field: "account",
          align: "center",
        },
        {
          title: "剩余充值",
          field: "recharge_points",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              if (row.recharge_points == 0) {
                return [h("div", "-")];
              } else return [h("div", row.recharge_points / 10000)];
            },
          },
        },
        {
          title: "剩余赠送",
          field: "bonus_points",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              if (row.bonus_points == 0) {
                return [h("div", "-")];
              } else return [h("div", row.bonus_points / 10000)];
            },
          },
        },
        {
          title: "用户充值积分",
          field: "points_consume_account",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              if (row.points_consume_account == 0) {
                return [h("div", "-")];
              } else return [h("div", row.points_consume_account / 10000)];
            },
          },
        },
        {
          title: "用户赠送积分",
          field: "points_consume_gift",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              if (row.points_consume_gift == 0) {
                return [h("div", "-")];
              } else return [h("div", row.points_consume_gift / 10000)];
            },
          },
        },
        // {
        //   title: "用户消耗积分",
        //   field: "points_consume_total",
        //   align: 'center',
        //   slots:{
        //     default:({row},h) =>{
        //       if(row.points_consume_total==0){
        //         return [h("div",'-')]
        //       }else
        //       return [h("div",row.points_consume_total/10000)]
        //     }
        //   }
        // },
        {
          title: "业务方案",
          field: "business_price_name",
          align: "center",
        },
        {
          title: "状态",
          field: "status",
          align: "center",
          slots: {
            default: ({ row }, h) => {
              // if(this.UserInfo.role=="代理商"){
              //     return [h("div",row.status==1?"正常":"冻结")]
              // }else{
              let disabled = false;
              if (this.Perm.add) {
                disabled = false;
              }
              return [
                h(
                  "iSwitch",
                  {
                    props: {
                      value: (1 & row.status) == 1 ? true : false,
                      disabled: disabled,
                      size: "large",
                    },
                    on: {
                      "on-change": (value) => {
                        let info = { id: row.id };
                        value == true
                          ? (this.handleType = 4)
                          : (this.handleType = 5);
                        this.updateInfo(info);
                      },
                    },
                  },
                  [
                    h("span", {
                      slot: "open",
                      domProps: {
                        innerHTML: "正常",
                      },
                    }),
                    h("span", {
                      slot: "close",
                      domProps: {
                        innerHTML: "冻结",
                      },
                    }),
                  ]
                ),
              ];
              // }
            },
          },
        },
        {
          title: "注册时间",
          field: "create_at",
          align: "center",
          width: 150,
          slots: {
            default: ({ row }, h) => {
              if (row.create_at == 0) {
                return [h("div", "-")];
              } else
                return [
                  h(
                    "div",
                    utils.dateFormat(row.create_at, "yyyy-MM-dd HH:mm:ss")
                  ),
                ];
            },
          },
        },
        {
          title: "操作",
          field: "action",
          width: 170,
          align: "center",
          slots: {
            default: ({ row }, h) => {
              return this.$AutoFun(() => {
                let hButton = [];
                hButton.push(
                  h("div", {
                    class: "looklook",
                    on: {
                      click: () => {
                        this.lookInfo(row);
                      },
                    },
                  })
                );
                hButton.push(
                  h("div", {
                    props: { type: "primary", size: "small" },
                    style: { marginRight: "5px" },
                    class: "two",
                    on: {
                      click: () => {
                        this.editInfo(row, 2);
                      },
                    },
                  })
                );
                hButton.push(
                  h("div", {
                    props: { type: "danger", size: "small" },
                    style: { marginRight: "5px" },
                    class: "three",
                    on: {
                      click: () => {
                        this.sureDel(row, -1);
                      },
                    },
                  })
                );
                hButton.push(
                  h("div", {
                    props: { type: "danger", size: "small" },
                    style: { marginRight: "5px" },
                    class: "one",
                    on: {
                      click: () => {
                        this.editInfo(row, 3);
                      },
                    },
                  })
                );

                return hButton;
              });
            },
          },
        },
      ],
      format: {
        account: {
          labelName: "账号",
          labelType: "text",
          placeholder: "请输入账号",
        },
        passwd: {
          labelName: "密码",
          labelType: "text",
          placeholder: "请输入密码",
        },
        tag: {
          labelName: "账号属性",
          labelType: "text",
          placeholder: "请选择账号属性",
        },
        business_price_id: {
          labelName: "业务方案",
          labelType: "select",
          labelValue: [],
          placeholder: "请选择业务方案",
        },
        prises: {
          label: "",
          labelType: "tableprice",
          labelValue: [],
          labelDisabled: true,
        },
      },
      ruleValidate: {
        role_id: [{ required: true, validator: validateRole, trigger: "blur" }],
        // leader_id: [{ required: true,validator:validateLeader, trigger: "blur" }],
        account: [
          { required: true, validator: validateaccount, trigger: "blur" },
        ],
        passwd: [
          { required: true, validator: validatepasswd, trigger: "blur" },
        ],
      },
      dateOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  computed: {
    ...mapGetters(["UserInfo"]),
  },
  methods: {
    async initView(isMounted) {
      console.log(isMounted, "isMounted");
      if (isMounted) {
        await this.getList();
        await this.initSearchData();
        if (window.$toEmit) {
          bus.$emit("userHasRender");
          window.$toEmit = false;
        }
      }
    },
    async initSearchData() {
      let res3 = await Request.post("customer/businessPrice", "query_list", {
        def: 1,
      }); //默认业务方案接口
      this.priceId = res3.data.list[0].id || "";
      let res4 = await Request.post(
        "customer/businessPrice",
        "queryDetail_item",
        { id: this.priceId, def: 1 }
      ); //筛料源接口
      let pricesList2 = res4.data || [];
      this.pList2 = pricesList2.map((item) => {
        return {
          id: item.id,
          name: item.name,
          desc: item.desc,
          unit_price: item.unit_price / 10000,
        };
      });
      this.initPrice();
    },
    onSearchGetList() {
      this.searchData.page_index = 1;
      this.getList();
    },
    async initPrice() {
      let res2 = await Request.post("customer/businessPrice", "query_list", {
        with_def: 1,
      }); //业务方案接口
      let pricesList = res2.data.list || [];
      this.pList = pricesList.map((item) => {
        return {
          id: item.id,
          name: item.name,
          desc: item.description,
        };
      });
    },
    onCheckChange(rows) {
      this.selectRows = [];
      this.selectRows = rows;
    },
    //查看
    async lookInfo(row) {
      let res2 = await Request.post("customer/businessPrice", "query_list", {
        id: row.business_price_id,
        with_def: 1,
      }); //业务方案接口
      let rowprice =
        this.priceId === row.business_price_id
          ? res2.data.list[0].prices || []
          : res2.data.list[1].prices || [];
      console.log(rowprice, "rowprice");
      let priceList = rowprice || [];
      priceList = priceList.map((item) => {
        const priceItem =
          this.pList2.find((item2) => item2.name === item.name) || {};
        return {
          name: item.name,
          desc: priceItem.desc,
          unit_price: priceItem.unit_price,
          price: item.unit_price / 10000,
        };
      });
      let info = {};
      info = {
        id: row.id,
        account: row.account,
        role_id: row.role_id,
        leader_id: row.leader_id,
        business_price_id: row.business_price_id,
        prises: priceList,
      };
      console.log(this.pList2, "this.pList2", priceList, "priceList");
      let title = "查看用户配置";
      this.format.business_price_id.labelValue = this.pList;
      this.format.prises.labelValue = priceList;
      this.handleType = 8;
      this.formPopIndex = await utils.showFormPage(
        { title: title, el: this.$parent.$el, width: 700, cancelBtnStatus: 0 },
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo
      );
    },
    ppliang() {
      if (
        (this.selectRows.checked == true &&
          this.selectRows.records.length != 0) ||
        (this.selectRows.checked == false &&
          this.selectRows.records.length != 0)
      ) {
        this.editInfo({}, 7);
      } else {
        utils.showSureModal({
          icon: require("../../assets/images/peach-svg/bluegth.svg"),
          modalContent: "请至少选择一项 ",
          title: "提示",
        });
      }
    },
    async getList() {
      utils.showLoading();
      if (this.business_price_id !== "") {
        this.searchData.business_price_id = this.business_price_id.join(",");
      }
      let res = await this.RequestPost("query_list", this.searchData);
      if (res.code == 0 && res.data != null) {
        this.list = [];
        if (res.data.list != null) this.list = res.data.list;
        this.totalCnt = res.data.total;
      }
      await utils.sleepMs(500);
      utils.hideLoading();
    },
    //添加 编辑用户
    async editInfo(row, type) {
      await this.initPrice();
      this.eid = row.id;
      this.handleType = type;
      let title = "";
      let info = {};
      if (this.handleType == 1) {
        title = "添加用户";
        this.format.account.labelDisabled = false;
        this.format.passwd.labelDisabled = false;
        this.format.business_price_id.labelValue = this.pList;
        info = {
          account: "",
          passwd: "",
          business_price_id: this.priceId,
        };
        this.onSelectChange("role_id", info.role_id);
      } else if (this.handleType == 2) {
        this.format.account.labelDisabled = false;
        this.format.passwd.labelDisabled = false;
        this.format.business_price_id.labelValue = this.pList;
        title = "编辑用户";
        info = {
          account: row.account,
          business_price_id: row.business_price_id,
        };
        this.onSelectChange("role_id", info.role_id);
      } else if (this.handleType == 3) {
        this.format.account.labelDisabled = true;
        // this.format.passwd.labelDisabled = true
        title = "重置密码";
        info = {
          account: row.account,
          passwd: "8888888a",
        };
      } else if (this.handleType === 7) {
        title = "批量修改方案";
        let ids = "";
        this.selectRows.records.forEach((item) => {
          ids += "|" + item.id;
        });
        if (ids != "") {
          ids = ids.substring(1);
        }
        info = {
          ids: ids,
          business_price_id: this.priceId,
        };
        this.format.business_price_id.labelValue = this.pList;
      }
      this.info = info;
      // if(this.handleType != 3){
      this.formPopIndex = await utils.showFormPage(
        { title: title, el: this.$parent.$el, width: 700, cancelBtnStatus: 0 },
        this.info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange
      );
      // }
    },
    async updateInfo(info) {
      utils.showLoading();
      let code = -1;
      let actionName = "";
      let tipText = "";
      let postData = utils.cloneObj(info);
      this.nameobj = [];
      if (true) {
        if (this.handleType == 1) {
          actionName = "add_item";
          tipText = "添加成功！";
          postData.account = postData.account.replace(/\s+/g, "");
        } else if (this.handleType == 2) {
          actionName = "edit_item";
          tipText = "编辑成功！";
          postData["id"] = this.eid;
          postData["account"] = postData.account.replace(/\s+/g, "");
        } else if (this.handleType == -1) {
          actionName = "del_item";
          tipText = "删除成功！";
          postData = { id: postData.Id };
        } else if (this.handleType == 3) {
          actionName = "resetPasswd_item";
          tipText = "修改成功";
          postData = { id: this.eid, passwd: postData.passwd };
        } else if (this.handleType == 4) {
          actionName = "enable_item";
          tipText = "启用成功！";
          postData = { id: postData.id };
        } else if (this.handleType == 5) {
          actionName = "disable_item";
          tipText = "冻结成功！！";
          postData = { id: postData.id };
        } else if (this.handleType == 7) {
          actionName = "edit_item";
          tipText = "批量修改成功！！";
        } else if (this.handleType === 8) {
          utils.hideFormPage(this.formPopIndex);
          utils.hideLoading();
          return;
        }
        if (
          this.handleType == 1 ||
          this.handleType == 2 ||
          this.handleType == -1
        ) {
          bus.$emit("update-recharge-account-list");
        }
        let res = await this.RequestPost(actionName, postData);
        code = res.code;
        if (code == 0) {
          utils.hideFormPage(this.formPopIndex);
          await utils.sleepMs(1000);
          utils.showTip(tipText);
        } else {
          utils.shadowModel({
            icon: require("../../assets/images/Frame 427318277.svg"),
            modalContent: res.data,
            title: "提交失败",
          });
        }
      }
      utils.hideLoading();
      this.getList();
    },
    //删除
    sureDel(item, type) {
      this.handleType = -1;
      utils.showSureModal(
        {
          title: "删除提示",
          icon: require("../../assets/images/peach-svg/Frame 427318277 (1).svg"),
          modalContent: "确认删除 " + item.id + " ?",
          callBackArgs: { Id: item.id },
        },
        (res) => {
          let code = res.code;
          if (code == 0) {
            let data = res.data;
            this.updateInfo(data);
          }
        }
      );
    },
    onChangePageSize(page, pageSize) {
      this.modal = true;
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate() {
      this.searchData.start = Date.parse(this.searchDate[0]) / 1000;
      this.searchData.end = Date.parse(this.searchDate[1]) / 1000 + 86400;
      this.onSearchGetList();
    },
    initDate() {
      let nowDay = "";
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay), new Date(endDay)];
      this.changeDate();
    },
    async onSelectChange(label, value, reset) {},
    slotHeader(h) {
      return [
        h("div", {
          class: { allCount: true },
          style: { "margin-left": "10px" },
        }),
      ];
    },
    filterPartner(item) {
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1) return true;
      return item.BusinessId == this.searchData.searchBusinessId;
    },
  },
  mounted() {
    bus.$on("user-count-list", (data) => {
      console.log("fiahjfio");
      this.list = data.list;
      this.totalCnt = data.total;
    });
    bus.$on("user-count-Id", (ID) => {
      this.business_price_id = [ID];
    });
  },
};
</script>
